package com.ruiao.car.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Data
@Slf4j
public class HeaderUtil {

    private static final long serialVersionUID = -2988099637051741258L;

    /***header信息***/
    private String auth;
    private String osType;
    private String appChannel;
    private String appVersion;
    private String deviceId;
    private String appId;
    private String appName;
    /***header信息***/
    /**
     * 1.0.0
     */
    private String version;
    //客户端ip
    private String ip;


    private String ts;//时间戳
    private String nonce;//请求唯一号
    private String signature;//签名
    private String token;



    public static HeaderUtil parseRequestToHeader(HttpServletRequest request) {
        if (request == null) {
            return null;
        }

        HeaderUtil header = new HeaderUtil();
        header.setAuth(request.getHeader("auth"));
        header.setToken(request.getHeader("token"));
        header.setOsType(request.getHeader("osType"));
        header.setAppChannel(request.getHeader("appChannel"));
        //header中appVersion存储格式为1.0.1(50)
        String appVersion = request.getHeader("appVersion");
        header.setAppVersion(appVersion);
        if (!StringUtils.isEmpty(appVersion) && appVersion.indexOf("(") != -1
                && appVersion.indexOf(")") != -1) {
            int startIndex = appVersion.indexOf("(");
            String version = appVersion.substring(0, startIndex);
            header.setVersion(version);
        }
        header.setDeviceId(request.getHeader("deviceId"));
        header.setAppId(request.getHeader("appId"));
        header.setAppName(request.getHeader("appName"));

        header.setTs(request.getHeader("ts"));
        header.setNonce(request.getHeader("nonce"));
        header.setSignature(request.getHeader("signature"));

        header.setIp(NetworkUtils.getIpAddress(request));

        log.debug("header头部为{}",header.toString());

        return header;

    }


    public static String versionTransfer(String version) {
        if (StringUtils.isBlank(version)) {
            return null;
        }
        String[] versionArray = version.split("\\.");
        String firstStr = String.format("%03d", Integer.parseInt(versionArray[0]));
        String secondStr = String.format("%03d", Integer.parseInt(versionArray[1]));
        String thirdStr = String.format("%04d", Integer.parseInt(versionArray[2]));
        return firstStr + "." + secondStr + "." + thirdStr;
    }
}
